package com.aiton.bamin.bamindaijiadrier.customview;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.activity.OrderIngActivity;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.Order;
import com.aiton.bamin.bamindaijiadrier.model.SendOrder;
import com.aiton.bamin.bamindaijiadrier.model.User;
import com.aiton.bamin.bamindaijiadrier.server.LocationService;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static com.aiton.bamin.bamindaijiadrier.R.id.order_dialog_list;
import static com.aiton.bamin.bamindaijiadrier.TTSController.ttsManager;

/**
 * Created by ykj on 15-12-25.
 */
public class OrderToast {

    Context mContext;
    WindowManager.LayoutParams params;
    WindowManager mWM;
    View mView;
    private MyAdapter mOrderAdapter;
    private List<SendOrder> mSendOrderList = new ArrayList<>();
    private List<SendOrder> mOrderList = new ArrayList<>();
    private final ListView mOrder_dialog_list;
    private List<Thread> mThreadList = new ArrayList<>();
    private List<Thread> mSecondThreadList = new ArrayList<>();
    private List<Boolean> isCancle = new ArrayList<>();
    private int orderCount = 0;
    private boolean isAddView;//弹窗是否在显示
    private User mUser;

    public OrderToast(Context context) {
        this.mContext = context;
        params = new WindowManager.LayoutParams();
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        Log.e("OrderToast ", "宽度" + params.width);
        params.format = PixelFormat.TRANSLUCENT;
        params.windowAnimations = R.style.anim_view;
        params.type = WindowManager.LayoutParams.TYPE_TOAST;
        params.gravity = Gravity.CENTER;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mWM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater inflate = (LayoutInflater)
                mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mView = inflate.inflate(R.layout.order_dialog, null);
        mOrder_dialog_list = (ListView) mView.findViewById(order_dialog_list);
        mOrderAdapter = new MyAdapter();
        mOrder_dialog_list.setAdapter(mOrderAdapter);
    }

    public void show(SendOrder sendOrder, User mUser) {
        this.mUser = mUser;
        orderCount = orderCount + 1;
        mSendOrderList.add(sendOrder);
        mOrderList.add(sendOrder);
        isCancle.add(false);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        mThreadList.add(thread);
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10001);
                    mSendOrderList.clear();
                    for (int i = 0; i < mThreadList.size(); i++) {
                        if (!isCancle.get(i)) {
                            if (mThreadList.get(i).isAlive()) {
                                Log.e("run ", "run 添加的order" + i);
                                mSendOrderList.add(mOrderList.get(i));
                            } else {
                                Intent intent = new Intent();
                                intent.putExtra(Constant.INTENT_KEY.AUTO_CANCLE_ORDER, mOrderList.get(i));
                                intent.setAction(Constant.BROADCASTCODE.SEND_ORDER_SERVER);
                                mContext.sendBroadcast(intent);
                            }
                        }
                    }
                    handler.sendEmptyMessage(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread2.start();
        mSecondThreadList.add(thread2);
        mOrderAdapter.notifyDataSetChanged();
        if (mSendOrderList.size() > 1) {

        } else {
            isAddView = true;
            mWM.addView(mView, params);
        }
    }
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            hide();
        }
    };
    public void hide() {
        if (mSendOrderList.size() > 0) {
            Log.e("hide ", "run 刷新适配器" + mSendOrderList.size());
            mOrderAdapter.notifyDataSetChanged();
        } else {
            hideView();
        }
    }
    private void hideView() {
        mThreadList.clear();
        mSecondThreadList.clear();
        orderCount = 0;
        mSendOrderList.clear();
        mOrderList.clear();
        isCancle.clear();
        if (isAddView) {
            isAddView = false;
            mWM.removeView(mView);
        }
    }
    class ViewHolder {
        TextView textView_start;
        TextView textView_end;
        TextView textView_HowLong;
        TextView textView_cost;
        TextView textView_fee;
        Button button_ignore;
        Button button_accept;

        public ViewHolder(TextView textView_start, TextView textView_end, TextView textView_HowLong, TextView textView_cost, TextView textView_fee, Button button_ignore, Button button_accept) {
            this.textView_start = textView_start;
            this.textView_end = textView_end;
            this.textView_HowLong = textView_HowLong;
            this.textView_cost = textView_cost;
            this.textView_fee = textView_fee;
            this.button_ignore = button_ignore;
            this.button_accept = button_accept;
        }
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mSendOrderList.size();
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View inflate = inflater.inflate(R.layout.get_order_item_server, null);
            TextView textView_start = (TextView) inflate.findViewById(R.id.textView_start);
            TextView textView_end = (TextView) inflate.findViewById(R.id.textView_end);
            TextView textView_HowLong = (TextView) inflate.findViewById(R.id.textView_HowLong);
            TextView textView_cost = (TextView) inflate.findViewById(R.id.textView_cost);
            TextView textView_fee = (TextView) inflate.findViewById(R.id.textView_fee);
            if (mSendOrderList.size() > 0) {
                Log.e("getView ", "getView 执行");
                inflate.findViewById(R.id.button_ignore).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        acceptOrderFailed(position);
                    }
                });
                inflate.findViewById(R.id.button_accept).setOnClickListener(new View.OnClickListener() {
                    long lastClick = 0;
                    @Override
                    public void onClick(View v) {
                        //大于一秒方个通过
                        if (System.currentTimeMillis() - lastClick <= 1000) {
                            return;
                        }
                        Log.e("MyAdapter", "toast点击接单" );

                        lastClick = System.currentTimeMillis();
                        aceptOrder(position);
                    }
                });
                SendOrder sendOrder = mSendOrderList.get(position);
                textView_start.setText(sendOrder.getStartLocation());
                textView_end.setText(sendOrder.getEndLocation());
                textView_HowLong.setText(sendOrder.getMileage() + "公里");
                textView_cost.setText(sendOrder.getMoney() + "");
                textView_fee.setText(sendOrder.getFee() + "");
                Log.e("MyAdapter", "getView: --->>" +sendOrder.getStartLocation() );
                Log.e("MyAdapter", "getView: --->>" +sendOrder.getEndLocation() );
                Log.e("MyAdapter", "getView: --->>" +sendOrder.getMileage() + "公里" );
                Log.e("MyAdapter", "getView: --->>" +sendOrder.getMoney() + "" );
                Log.e("MyAdapter", "getView: --->>" +sendOrder.getFee() + "" );
            }
            return inflate;
        }
    }
    private void acceptOrderFailed(int position) {
        SendOrder sendOrder = mSendOrderList.get(position);
        Log.e("onClick ", "onClick 取消" + position);
        for (int i = 0; i < mOrderList.size(); i++) {
            boolean contains = mOrderList.contains(sendOrder);
            if (contains) {
                isCancle.set(i, true);
                break;
            }
        }
        mSendOrderList.remove(position);
        hide();
    }

    /**
     * 司机接单
     *
     * @param position
     */
    private void aceptOrder(final int position) {
        String url = Constant.Url.ACECPT_ORDER;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        SendOrder sendOrder = mSendOrderList.get(position);
        params.put("orderId", sendOrder.getOrderId());
        params.put("driverId", mUser.getDatas().getId() + "");
        params.put("driverPhone", mUser.getDatas().getPhone());
        params.put("driverName", mUser.getDatas().getName());
        params.put("driverCoordinate", LocationService.mLocationLatLng.longitude + "," + LocationService.mLocationLatLng.latitude);
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
                    Log.e("onSuccess ", "接受订单返回值" + s);
                    Order order = GsonUtils.parseJSON(s, Order.class);
                    int status = order.getStatus();
                    ttsManager.stopSpeaking();
                    ttsManager.startSpeaking();
                    if (status == 0) {
                        Intent intent = new Intent();
                        intent.setAction(Constant.BROADCASTCODE.STOP_GET_ORDER);
                        mContext.sendBroadcast(intent);
                        ttsManager.playText("抢单成功");
                        for (int i = 0; i < mOrderList.size(); i++) {
                            isCancle.add(i, true);
                        }
                        Log.e("onSuccess ", "onSuccess 准备跳转1");
                        Intent intent1 = new Intent();
                        Log.e("onSuccess ", "onSuccess 准备跳转2");
                        intent1.putExtra(Constant.INTENT_KEY.ORDER_ING, order);
                        Log.e("onSuccess ", "onSuccess 准备跳转3");
                        intent1.setClass(mContext, OrderIngActivity.class);
                        Log.e("onSuccess ", "onSuccess 准备跳转4");
                        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent1);
                        Log.e("onSuccess ", "onSuccess 跳转完成5");
                        hideView();
                        Log.e("onSuccess ", "onSuccess 跳转完成隐藏6");
                    } else if (status == 1) {
                        ttsManager.playText("抢单失败");
                        Toast.makeText(mContext, "抢单失败", Toast.LENGTH_SHORT).show();
                        acceptOrderFailed(position);
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

}
